package com.vehicle.repair.service;

import com.vehicle.repair.model.MaterialUsage;
import com.vehicle.repair.model.WorkOrder;
import com.vehicle.repair.repository.MaterialUsageRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class MaterialService {
    private final MaterialUsageRepository materialUsageRepository;
    private final WorkOrderService workOrderService;

    public MaterialService(MaterialUsageRepository materialUsageRepository, 
                         WorkOrderService workOrderService) {
        this.materialUsageRepository = materialUsageRepository;
        this.workOrderService = workOrderService;
    }

    public MaterialUsage addMaterialUsage(MaterialUsage materialUsage, Integer orderId) {
        WorkOrder order = workOrderService.getWorkOrderById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Work order not found"));
        
        materialUsage.setOrder(order);
        MaterialUsage savedUsage = materialUsageRepository.save(materialUsage);
        
        // Update order total cost
        updateOrderTotalCost(orderId);
        
        return savedUsage;
    }

    public Optional<MaterialUsage> getMaterialUsageById(Integer id) {
        return materialUsageRepository.findById(id);
    }

    public List<MaterialUsage> getMaterialUsagesByOrder(Integer orderId) {
        WorkOrder order = workOrderService.getWorkOrderById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Work order not found"));
        return materialUsageRepository.findByOrder(order);
    }

    public void deleteMaterialUsage(Integer id) {
        MaterialUsage usage = materialUsageRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Material usage not found"));
        
        Integer orderId = usage.getOrder().getOrderId();
        materialUsageRepository.deleteById(id);
        
        // Update order total cost
        updateOrderTotalCost(orderId);
    }

    private void updateOrderTotalCost(Integer orderId) {
        WorkOrder order = workOrderService.getWorkOrderById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Work order not found"));
        
        double materialCost = materialUsageRepository.findByOrder_OrderId(orderId)
                .stream()
                .mapToDouble(MaterialUsage::getTotalPrice)
                .sum();
        
        // TODO: Add labor cost calculation
        order.setTotalCost(materialCost);
        workOrderService.updateWorkOrderStatus(orderId, order.getStatus());
    }
}
